package com.billionsfinance.hessian.common.zookeeper.server;

import com.billionsfinance.hessian.common.utils.ZkConfig;
import com.billionsfinance.hessian.model.ServerInfo;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * zookeeper注册服务
 *
 * @ ClassName: ServerSideZkThread.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/23 14:59
 * @ Version: v1.0.0
 */
public class ServerSideZkThread implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerSideZkThread.class);

    private Set<ServerInfo> servers;

    private ZkConfig zkConfig;

    private CuratorFramework curatorFramework;

    public ServerSideZkThread(ZkConfig zkConfig, Set<ServerInfo> servers) {
        this.zkConfig = zkConfig;
        this.servers = servers;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        LOGGER.info("current running thread :{}", name);

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 20);

        curatorFramework = CuratorFrameworkFactory.builder() //
                .connectString(zkConfig.getConnectString()) //  连接zookeeper的地址
                .sessionTimeoutMs(zkConfig.getSessionTimeoutMs())  //session 超时时间
                .connectionTimeoutMs(zkConfig.getConnectionTimeoutMs()) // 连接超时时间
                .retryPolicy(retryPolicy)  //重试策略
                .build();

        ServerSideZkConnectionStateListener listener = new ServerSideZkConnectionStateListener(servers);

        curatorFramework.getConnectionStateListenable().addListener(listener);

        curatorFramework.start();
    }

    public void close() {
        curatorFramework.close();
    }
}
